package cn.xx.user.interceptor;

import cn.xx.user.domain.LoginInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 登录拦截器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 在请求目标方法之前，被拦截
     * @param request
     * @param response
     * @param handler
     * @return
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        //获取请求头信息token
        String token = request.getHeader("TOKEN");
        if(StringUtils.isEmpty(token)){
            //就要被拦截跳转到登录界面
            writeJson(response);//手动响应结果值
            return false;
        }

        //根据token获取登录用户信息
        LoginInfo loginInfo = (LoginInfo) redisTemplate.opsForValue().get(token);

        //如果loginInfo为空，就证明是redis已经过期了
        if(loginInfo==null){
            //就要被拦截跳转到登录界面
            writeJson(response);//手动响应结果值  添加请求头结果值
            return false;
        }

        //把登录信息放到redis
        redisTemplate.opsForValue().set(token, loginInfo, 30, TimeUnit.MINUTES);

        return true;
    }
    // 添加请求头
    private void writeJson(HttpServletResponse response) throws IOException {
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write("{\"success\":false,\"msg\":\"NoLogin\"}");
    }
}
